package itsm.isperp.module.controller.configuration;

import itsm.isperp.framework.collection.tree.ITreeNode;
import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.domain.IBean;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.sequence.SequenceGenerator;
import itsm.isperp.framework.sequence.SequenceUtils;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.utils.JsonBuilder;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.framework.web.request.JqGridFilter;
import itsm.isperp.framework.web.request.JqGridFilterRule;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.dto.db.DbEntityFieldToUiControler;
import itsm.isperp.module.entity.app.AppDict;
import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.entity.change.ChgChangeConfiguration;
import itsm.isperp.module.entity.configuration.ConfCategory;
import itsm.isperp.module.entity.configuration.ConfCi;
import itsm.isperp.module.entity.configuration.ConfCiProperty;
import itsm.isperp.module.entity.customer.CusCustomer;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.change.ChgChangeConfigurationService;
import itsm.isperp.module.service.configuration.ConfCategoryService;
import itsm.isperp.module.service.configuration.ConfCiPropertyDatalogService;
import itsm.isperp.module.service.configuration.ConfCiService;
import itsm.isperp.module.service.customer.CusCustomerService;
import itsm.isperp.module.utils.EchartGraphLinkUtils;
import itsm.isperp.module.utils.MatrixToImageWriters;
import itsm.isperp.module.utils.ProjectDomainUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 配置项管理控制器
 * 
 * @author lizx
 * @date 2013-4-30
 */
@Controller
@RequestMapping("configuration/ci")
public class ConfCiController extends BaseController<ConfCi> {

  @Autowired
  ConfCiService confCiService;

  @Autowired
  ConfCategoryService confCategoryService;

  @Autowired
  CusCustomerService cusCustomerService;

  @Autowired
  ChgChangeConfigurationService chgChangeConfigurationService;

  @Autowired
  ConfCiPropertyDatalogService confCiPropertyDatalogService;

  @Override
  public ConfCiService getService() {
    return confCiService;
  }

  @Override
  public String getPageTitle() {
    return "配置项";
  }

  @Override
  @RequestMapping(value = { "manage", "" })
  public ModelAndView manage(HttpServletRequest req) {

    ModelAndView mv = this.getModelAndView();
    List<Map<String, Object>> list = cusCustomerService.getCustomerCiCount();
    mv.addObject("customerCiCounts", list);
    mv.addObject("customerCiSize", list.size());
    if (list.size() == 1) {
      Map<String, Object> cusCustomer = list.get(0);
      mv.addObject("cusCustomerId", cusCustomer.get("id").toString());
    } else {
      mv.addObject("cusCustomerId", "");
    }
    String showAddBtn = "1";
    int dataRange = ProjectDomainUtils.getUserMaxDataRange();
    if (dataRange == 22 || dataRange == 33)
      showAddBtn = "0";
    mv.addObject("showAddBtn", showAddBtn);
    AppDictService appDictService = ContextHolder
        .getSpringBean("appDictService");
    mv.addObject("var_assetStatus", appDictService.findByType("CI_STATUS"));
    return mv;
  }

  /**
   * 编辑界面
   * 
   * @param id
   *          唯一标识
   * @return 编辑视图
   */
  @Override
  @RequestMapping("edit")
  public ModelAndView edit(String id, HttpServletRequest req) {
    ModelAndView mv = new ModelAndView(this.getModulePath() + "/edit");
    ConfCi model = null;

    String code = req.getParameter("code");

    String customerId = req.getParameter("customerId");
    String categoryId = req.getParameter("categoryId");
    String userId = req.getParameter("userId");
    String changeId = req.getParameter("changeId");
    IUser curUser = ContextHolder.getLoginUser();
    int editStatus = 1;

    // 生成编号

    SequenceGenerator sg = ContextHolder.getSpringBean("sequenceGenerator");
    String seq = sg.next("conf_ci");

    if (StringUtils.isEmpty(id)) {

      if (StringUtils.isNotEmpty(code)) {
        model = this.getService().findOneByCode(code);
      }

      if (model == null) {
        model = new ConfCi();
        editStatus = 1;
        model.setId(HibernateUUIDGenerator.generate());
        model.setCreator(curUser.getUsername());
        model.setCreatorName(curUser.getFullname());
        model.setCode(seq);

        if (StringUtils.isNotEmpty(customerId)) {
          CusCustomer cus = cusCustomerService.findOne(customerId);
          model.setCusCustomerId(cus.getId());
          model.setCusCustomerName(cus.getName());
        }

        if (StringUtils.isNotEmpty(categoryId)) {
          model.setConfCategoryId(categoryId);
          ConfCategory category = confCategoryService.findOne(categoryId);
          if (null != category) {
            model.setConfCategoryName(category.getTreenodeNamePath());
          }
        }

        if (StringUtils.isNotEmpty(userId)
            && StringUtils.isEmpty(model.getUseStaffId())) {

          AppUserService appUserService = ContextHolder
              .getSpringBean("AppUserService");
          AppUser u = appUserService.findOne(userId);
          if (null != u) {
            model.setUseStaffId(u.getId());
            model.setUseStaffName(u.getName());
          }
        }
      }
    } else {
      model = this.getService().findOne(id);
      editStatus = 2;

      // if (StringUtils.isNotEmpty(model.getCusCustomerId())) {
      // CusCustomerService cusCustomerService = ContextHolder
      // .getSpringBean("cusCustomerService");
      // mv.addObject("cusCustomerName",
      // cusCustomerService.findOne(model.getCusCustomerId())
      // .getName());
      // }

    }
    String readonly = req.getParameter("readonly");
    if (readonly != null && (readonly.equals("1") || readonly.equals("true"))) {
      editStatus = 0;
    }

    AppDictService appDictService = ContextHolder
        .getSpringBean("appDictService");
    mv.addObject("ciStatus", appDictService.findByType("CI_STATUS"));

    mv.addObject("ciSecret", appDictService.findByType("CI_SECRET"));

    mv.addObject("model", model);
    mv.addObject("pageTitle", this.getPageTitle());
    mv.addObject("categoryId", categoryId);

    mv.addObject("changeId", changeId);
    mv.addObject("editStatus", editStatus);
    mv.addObject("readonly", readonly);
    // sparepartIn:入库申请添加的资产
    String ty = req.getParameter("ty");
    if (StringUtils.isNotEmpty(ty)) {
      mv.addObject("ty", ty);
      String sourceId = req.getParameter("sourceId");
      mv.addObject("sourceId", sourceId);
      if (ty.equals("sparepartIn")) {

        if (StringUtils.isEmpty(id)) {
          // 设置默认值
          CusCustomer cus = cusCustomerService.getCompanyCustomer();
          model.setCusCustomerId(cus.getId());
          model.setCusCustomerName(cus.getName());
          model.setStatusTemp("在库");

          // 设置供应商
          JdbcTemplate jdbcTemplate = ContextHolder
              .getSpringBean("jdbcTemplate");
          String sql1 = "SELECT * FROM spt_sparepart_in a where a.id='"
              + sourceId + "'";
          List<Map<String, Object>> mp1 = jdbcTemplate.queryForList(sql1);
          if (mp1.size() > 0) {
            if (mp1.get(0).get("provider_id") != null)
              model.setProvider(mp1.get(0).get("provider_id").toString());
          }
          model.setUseStaffIdTemp(curUser.getId());
          model.setUseStaffNameTemp(curUser.getFullname());
        } else {
          mv.addObject("id", id);
        }

        mv.setViewName(this.getModulePath() + "/sparepartCiEdit");

      } else if (ty.equals("sparepartOut")) {
        // 设置默认值
        /*
         * model.setStatusTemp("在库"); model.setUseStaffIdTemp(curUser.getId());
         * model.setUseStaffNameTemp(curUser.getFullname());
         */
        mv.setViewName(this.getModulePath() + "/sparepartCiEdit");

      } else if (ty.equals("sparepartDiscard")) {
        // 设置默认值
        model.setStatusTemp("报废");
        model.setUseStaffIdTemp(curUser.getId());
        model.setUseStaffNameTemp(curUser.getFullname());
        mv.setViewName(this.getModulePath() + "/sparepartCiEdit");

      } else if (ty.equals("sparepartBack")) {
        // 设置默认值
        // model.setStatusTemp("在库坏件");
        /*
         * model.setUseStaffIdTemp(curUser.getId());
         * model.setUseStaffNameTemp(curUser.getFullname());
         */
        mv.setViewName(this.getModulePath() + "/sparepartCiEdit");

      }
    }

    return mv;

  }

  @RequestMapping("auditEdit")
  public ModelAndView auditEdit(String id, HttpServletRequest req) {
    ModelAndView mv = new ModelAndView(this.getModulePath() + "/auditEdit");
    String ids = req.getParameter("ids");
    mv.addObject("ids", ids);
    return mv;

  }

  @RequestMapping("saveAuditCi")
  @ResponseBody
  public ResultMessage saveAuditCi(HttpServletRequest req) {

    String ids = req.getParameter("ids");
    String auditResult = req.getParameter("auditResult");
    String auditDate = req.getParameter("auditDate");

    confCiService.saveAuditCi(ids, auditResult, auditDate);

    return ResultMessage.success("");
  }

  /**
   * 变更编辑界面
   * 
   * @param id
   *          唯一标识
   * @return 编辑视图
   */
  @RequestMapping("changeEdit")
  public ModelAndView changeEdit(String id, HttpServletRequest req) {
    ModelAndView mv = new ModelAndView(this.getModulePath() + "/changeEdit");
    ConfCi model = null;

    String code = req.getParameter("code");

    String customerId = req.getParameter("customerId");
    String categoryId = req.getParameter("categoryId");
    String userId = req.getParameter("userId");
    String changeId = req.getParameter("changeId");
    int editStatus = 0;
    if (StringUtils.isEmpty(id)) {

      if (StringUtils.isNotEmpty(code)) {
        model = this.getService().findOneByCode(code);
      }

      if (model == null) {
        model = new ConfCi();
        editStatus = 1;
        model.setId(HibernateUUIDGenerator.generate());
        model.setCreator(ContextHolder.getLoginUser().getUsername());
        model.setCreatorName(ContextHolder.getLoginUser().getFullname());

        if (StringUtils.isNotEmpty(customerId)) {
          CusCustomer cus = cusCustomerService.findOne(customerId);
          model.setCusCustomerId(cus.getId());
          model.setCusCustomerName(cus.getName());
        }

        if (StringUtils.isNotEmpty(categoryId)) {
          model.setConfCategoryId(categoryId);
          ConfCategory category = confCategoryService.findOne(categoryId);
          if (null != category) {
            model.setConfCategoryName(category.getTreenodeNamePath());
          }
        }

        if (StringUtils.isNotEmpty(userId)
            && StringUtils.isEmpty(model.getUseStaffId())) {

          AppUserService appUserService = ContextHolder
              .getSpringBean("appUserService");
          AppUser u = appUserService.findOne(userId);
          if (null != u) {
            model.setUseStaffId(u.getId());
            model.setUseStaffName(u.getName());
          }
        }
      }
    } else {
      model = this.getService().findOne(id);

      // if (StringUtils.isNotEmpty(model.getCusCustomerId())) {
      // CusCustomerService cusCustomerService = ContextHolder
      // .getSpringBean("cusCustomerService");
      // mv.addObject("cusCustomerName",
      // cusCustomerService.findOne(model.getCusCustomerId())
      // .getName());
      // }

    }

    AppDictService appDictService = ContextHolder
        .getSpringBean("appDictService");
    mv.addObject("ciStatus", appDictService.findByType("CI_STATUS"));

    mv.addObject("ciSecret", appDictService.findByType("CI_SECRET"));

    mv.addObject("model", model);
    mv.addObject("pageTitle", this.getPageTitle());
    mv.addObject("categoryId", categoryId);

    mv.addObject("changeId", changeId);
    mv.addObject("editStatus", editStatus);
    return mv;

  }

  @RequestMapping("batchUpdateEdit")
  public ModelAndView batchUpdateEdit(String id, HttpServletRequest req) {
    ModelAndView mv = this.edit(null, req);

    ConfCi model = (ConfCi) mv.getModel().get("model");
    IUser u = ContextHolder.getLoginUser();
    model.setFinalChanger(u.getFullname());
    model.setFinalChangedDate(new Timestamp(new Date().getTime()));
    mv.setViewName(this.getModulePath() + "/batchUpdateEdit");

    mv.addObject("customerCiCounts", cusCustomerService.getCustomerCiCount());

    AppDictService appDictService = ContextHolder
        .getSpringBean("appDictService");
    mv.addObject("var_assetStatus", appDictService.findByType("CI_STATUS"));

    mv.addObject("var_secretLevel", appDictService.findByType("CI_SECRET"));

    return mv;

  }

  @RequestMapping("batchUpdate")
  @ResponseBody
  public ResultMessage batchUpdate(ConfCi model, HttpServletRequest req) {

    String changeId = req.getParameter("changeId");
    String customerId = req.getParameter("customerId");
    String categoryId = req.getParameter("categoryId");
    String fs = req.getParameter("filter");
    JqGridFilter filter = JsonBuilder.buildNormalBinder().fromJson(fs,
        JqGridFilter.class);
    List<JqGridFilterRule> rules = new ArrayList<JqGridFilterRule>();
    for (JqGridFilterRule rule : filter.getRules()) {
      if (StringUtils.isNoneEmpty(rule.getField())) {
        rules.add(rule);
      }
    }
    filter.setRules(rules);

    filter.addRule("cus_customer_id", JqGridFilterRuleOp.eq, customerId);

    filter.addRule("conf_category_id", JqGridFilterRuleOp.eq, categoryId);
    List<Map<String, String>> ps = new ArrayList<>();
    for (int i = 1; i < 5; i++) {

      String p = req.getParameter("p" + i);

      if (StringUtils.isNotEmpty(p)) {

        String op = req.getParameter("p" + i + "op");
        String value = req.getParameter("p" + i + "value");
        // String name = req.getParameter("p" + i + "name");

        // 得到动态列
        Map<String, String> pMap = new HashMap<String, String>();

        pMap.put("pColumn", "p" + i);
        pMap.put("pId", p);
        pMap.put("pValue", value);
        pMap.put("pOp", op);
        ps.add(pMap);
      }

    }

    String propertyList = req.getParameter("propertyList");

    ConfCiProperty[] ciPropertyArr = JsonBuilder.buildNormalBinder().fromJson(
        propertyList, ConfCiProperty[].class);
    List<ConfCiProperty> list = new ArrayList<ConfCiProperty>();

    if (ciPropertyArr != null) {
      for (ConfCiProperty item : ciPropertyArr) {
        list.add(item);
      }
    }

    int count = this.getService().batchUpdate(changeId, model, list, req, ps,
        filter);

    return ResultMessage.success(count);

  }

  /**
   * 保存实体
   * 
   * @param model
   *          　一个继承与IBean接口的尸体　{@link IBean}
   * @param req
   *          {@link HttpServletRequest} http请求
   * @return json结果数据
   */
  @RequestMapping("save")
  @ResponseBody
  @Override
  public ResultMessage save(ConfCi model, HttpServletRequest req) {

    String propertyList = req.getParameter("propertyList");
    String changeId = req.getParameter("changeId");

    // 资产变更流程，在审批后才更新资产属性
    if (changeId != null && !changeId.equals("")) {

      String changeConfigurationList = req
          .getParameter("changeConfigurationList");

      // 如果是在资产变更保存资产配置，则执行资产变更保存策略
      ChgChangeConfiguration[] chgconfArr = JsonBuilder.buildNormalBinder()
          .fromJson(changeConfigurationList, ChgChangeConfiguration[].class);

      if (chgconfArr != null && chgconfArr.length > 0) {
        for (ChgChangeConfiguration item : chgconfArr) {
          String tchangeId = item.getChangeId();
          String ciId = item.getCiId();
          String columnkey = item.getColumnkey();
          chgChangeConfigurationService.deleteChangeConfCi(tchangeId, ciId,
              columnkey);
          chgChangeConfigurationService.saveOrUpdate(item);
        }
        return ResultMessage.success(model.getId());
      } else {
        return ResultMessage.success(model.getId());
      }
    }

    ConfCiProperty[] ciPropertyArr = JsonBuilder.buildNormalBinder().fromJson(
        propertyList, ConfCiProperty[].class);

    List<ConfCiProperty> list = new ArrayList<ConfCiProperty>();

    if (ciPropertyArr != null) {
      for (ConfCiProperty item : ciPropertyArr) {
        list.add(item);
      }
    }
    String tempCustomerId = model.getCusCustomerId();
    String companyCustomerId = cusCustomerService.getCompanyCustomer().getId();

    if (model.getAreCompany() == null
        && tempCustomerId.equals(companyCustomerId)) {
      model.setAreCompany(1);
    }

    int r = this.getService().saveOrUpdate(changeId, model, list, req);

    // 更新关联资产的状态
    String nowStatus = model.getStatus();
    JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");

    String sql = "UPDATE conf_ci SET STATUS='"
        + nowStatus
        + "' WHERE id IN("
        + "SELECT to_id  FROM conf_ci_relation a INNER JOIN conf_ci_relation_type b ON a.relation_type_id=b.id"
        + " WHERE b.if_status_update='是' AND from_id='" + model.getId() + "')";
    jdbcTemplate.update(sql);

    if (r == 0) {
      return ResultMessage.failure("编号已存在");
    }

    return ResultMessage.success(model.getId());
  }

  /**
   * 根据id获取值
   * 
   * @param id
   * @return
   */
  @RequestMapping("listProperty")
  @ResponseBody
  public List<ConfCiProperty> listProperty(String id) {
    return this.getService().getCiProperty(id);

  }

  @RequestMapping("listByCusUserId")
  @ResponseBody
  public PageResponse<ConfCi> listByCusUserId(String cusUserId,
      JqGridRequest req) {

    return this.getService().findByCusUserId(cusUserId, req).toPage();
  }

  @RequestMapping("listSparepartCiByCusUserName")
  @ResponseBody
  public Page<ConfCi> listSparepartCiByCusUserName(String cusUserName,
      String typeKey, String sparepartId, HttpServletRequest request,
      JqGridRequest req) {
    AppUserService appUserService = ContextHolder
        .getSpringBean("appUserService");

    AppUser us = appUserService.findByUsername(cusUserName, "id", "name",
        "fullname");
    String cusUserId = "";
    String searchSql = "";
    if (us != null)
      cusUserId = us.getId();
    if (("null".equals(cusUserId) || StringUtils.isEmpty(cusUserId))
        || typeKey.equals("sparepartBack")) {
      searchSql = "(are_company=1) and  id not in(SELECT ci_id FROM spt_sparepart_relation a left JOIN v_sparepart_all b ON a.sparepart_id=b.id WHERE ((b.id IS NOT NULL AND a.type_key<>'sparepartIn' AND b.STATUS<>'已关闭' and b.process_id is not null) or (a.sparepart_id='"
          + sparepartId + "')))";
    } else {
      searchSql = String
          .format(
              "(are_company=1) and  ( id not in(SELECT ci_id FROM spt_sparepart_relation a left JOIN v_sparepart_all b ON a.sparepart_id=b.id WHERE (b.id IS NOT NULL AND a.type_key<>'sparepartIn' AND b.STATUS<>'已关闭' and b.process_id is not null) or (a.sparepart_id='"
                  + sparepartId
                  + "')) ) and  (use_staff_id='%s' OR management_staff_id='%s' OR support_staff_id='%s')",
              cusUserId, cusUserId, cusUserId);
    }
    if (StringUtils.isNotEmpty(typeKey) && typeKey.equals("sparepartBack")) {
      searchSql += " and id in (select c1.id from spt_sparepart_relation a1"
          + " inner join spt_sparepart_out b1 on a1.sparepart_id=b1.id"
          + " inner join conf_ci c1  on a1.ci_id=c1.id"
          + " where b1.use_man_id='" + cusUserName + "' and  a1.status=1)";
      String fromId = request.getParameter("fromId");
      String fromProcessKey = request.getParameter("fromProcessKey");
      if (StringUtils.isNotEmpty(fromId)) {
        searchSql += " and id in(SELECT ci_id FROM spt_sparepart_relation WHERE sparepart_id IN(SELECT to_id FROM bpm_process_relation WHERE from_type='"
            + fromProcessKey
            + "' AND from_id='"
            + fromId
            + "' AND to_type='sparepartOutProcess'))";
      }
    }
    req.setSearchString(searchSql);

    return this.getService().findAll(req);
  }

  @RequestMapping("listCiForPortal")
  @ResponseBody
  public Page<Map<String, Object>> listCiForPortal(HttpServletRequest req,
      JqGridRequest request) throws UnsupportedEncodingException {

    String fromType = req.getParameter("fromType");
    String condition = "";
    if (StringUtils.isNotEmpty(fromType) && fromType.equals("portal")) {
      String key = req.getParameter("key");
      String value = req.getParameter("value");
      condition = EchartGraphLinkUtils.getSql(key, value);
      condition = condition.replace("='空'", " is null ");
    }
    request.setSearchString(condition
        + " and (are_company is null or are_company=0)");
    return this.getService().listCiMapForPortalByRequest(request).toPage();
  }

  @RequestMapping("listCi")
  @ResponseBody
  public Page<Map<String, Object>> listCi(HttpServletRequest req,
      JqGridRequest request) throws UnsupportedEncodingException {

    String customerId = req.getParameter("customerId");
    String categoryNamePath = req.getParameter("categoryNamePath");
    String ciRelationTypeId = req.getParameter("ciRelationType");
    String ty = req.getParameter("ty");
    String searchStr = "";
    if (StringUtils.isNotEmpty(ty) && ty.equals("companyCi")) {
      request.addFilterRule("are_company", JqGridFilterRuleOp.eq, "1");
      customerId = this.cusCustomerService.getCompanyCustomer().getId();
    } else {
      searchStr += "(are_company is null or are_company=0)";
    }
    if (StringUtils.isNotEmpty(customerId)) {
      request.addFilterRule("cus_customer_id", JqGridFilterRuleOp.eq,
          customerId);
    }

    if (StringUtils.isNotEmpty(categoryNamePath))
      request.addFilterRule("treenode_category_name", JqGridFilterRuleOp.bw,
          categoryNamePath);

    List<Map<String, String>> ps = new ArrayList<>();
    for (int i = 1; i < 5; i++) {

      String p = req.getParameter("p" + i);
      if (StringUtils.isNotEmpty(p)) {

        String op = req.getParameter("p" + i + "op");
        String value = req.getParameter("p" + i + "value");
        value = java.net.URLDecoder.decode(value, "UTF-8");
        // String name = req.getParameter("p" + i + "name");

        // 得到动态列
        Map<String, String> pMap = new HashMap<String, String>();

        pMap.put("pColumn", "p" + i);
        pMap.put("pId", p);
        pMap.put("pValue", value);
        pMap.put("pOp", op);
        ps.add(pMap);
      }

    }
    if (StringUtils.isNotBlank(ciRelationTypeId)) {
      if ((ps != null && ps.size() > 0)) {
        searchStr += " and exists(select 1 from (select from_id,to_id,relation_type_id from conf_ci_relation)cr where cr.relation_type_id='"
            + ciRelationTypeId + "' and (cr.from_id=a.id or cr.to_id=a.id))";
      } else {
        searchStr += " and exists(select 1 from (select from_id,to_id,relation_type_id from conf_ci_relation)cr where cr.relation_type_id='"
            + ciRelationTypeId + "' and (cr.from_id=t.id or cr.to_id=t.id))";
      }

    }
    if (StringUtils.isNotBlank(searchStr))
      request.setSearchString(searchStr);
    return this.getService().listCiMapByRequest(ps, request).toPage();

  }

  // ～ --------------------------- ci 履历-----------------------------
  // /**
  // * 资产履历
  // *
  // * @param id
  // * 唯一标识
  // * @return 编辑视图
  // */
  // @RequestMapping("ciFailureResumeView")
  // public ModelAndView viewCiFailureResume(String id, HttpServletRequest
  // req) {
  //
  // ModelAndView mv = new ModelAndView(this.getModulePath()
  // + "/ciFailureResumeView");
  //
  // List<IcdIncident> list = confCiService.findCiIncident(id);
  // mv.addObject("incedentEntities", list);
  //
  // return mv;
  // }

  /**
   * 配置项（资产）履历
   * 
   * @param ciId
   *          唯一标识
   * @param keyword
   *          关键字（标红）
   * @return 资产履历界面
   */
  @RequestMapping(value = { "ciResume", "ciResumeView" })
  public ModelAndView ciResume(String id, String keyword, String type) {
    ModelAndView mv = this.getModelAndView();

    if (type != null && type.equals("ciaudit")) {
      JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
      String sql = "select * from tsk_inspect_ci_info where id='" + id + "'";
      List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
      if (list.size() > 0) {
        id = (String) list.get(0).get("ci_id");
      }
    }
    if (StringUtils.isNotEmpty(id)) {

      mv.addObject("model", confCiService.findOne(id));

      // List<IcdIncident> list = confCiService.findCiIncident(ciId);

      List<Map<String, Object>> list = confCiService.findCiIncidentDetail(id);
      mv.addObject("incedentEntities", list);

      List<Map<String, Object>> changeList = confCiService.findCiChange(id);
      mv.addObject("changeEntities", changeList);

      List<Map<String, Object>> dataChangeList = confCiPropertyDatalogService
          .findByBusinessId(id);
      mv.addObject("dataChangeEntities", dataChangeList);

    }
    return mv;

  }

  /**
   * 配置项变更（资产）履历
   * 
   * @param id
   *          唯一标识
   * @param keyword
   *          关键字（标红）
   * @return 资产变更履历界面
   */
  @RequestMapping("ciChangeResume")
  public ModelAndView ciResumeChange(String id) {
    // ModelAndView mv = this.getModelAndView();

    ModelAndView mv = new ModelAndView(this.getModulePath() + "/ciChangeResume");

    if (StringUtils.isNotEmpty(id)) {

      List<Map<String, Object>> changeList = confCiService.findCiChange(id);
      mv.addObject("changeEntities", changeList);
    }
    return mv;

  }

  @RequestMapping("ciAuditResume")
  public ModelAndView ciAuditResume(String id) {
    // ModelAndView mv = this.getModelAndView();

    ModelAndView mv = new ModelAndView(this.getModulePath() + "/ciAuditResume");
    return mv;

  }

  @RequestMapping("ciInspectResume")
  public ModelAndView ciInspectResume(String id) {
    // ModelAndView mv = this.getModelAndView();

    ModelAndView mv = new ModelAndView(this.getModulePath()
        + "/ciInspectResume");

    if (StringUtils.isNotEmpty(id)) {

      List<Map<String, Object>> inspectEntities = confCiService
          .findCiInspect(id);

      Map<String, List<Map<String, Object>>> newMap = new LinkedHashMap<>();

      List<Map<String, Object>> newList = new ArrayList<>();

      for (Map<String, Object> map : inspectEntities) {

        String taskId = map.get("task_id").toString();

        if (newMap.containsKey(taskId)) {
          newMap.get(taskId).add(map);

        } else {
          List<Map<String, Object>> v = new ArrayList<>();
          v.add(map);
          newList.add(map);
          newMap.put(taskId, v);
        }
      }
      mv.addObject("inspectEntities", newMap);
      mv.addObject("inspectList", newList);

    }
    return mv;

  }

  /**
   * 配置项故障（资产）履历
   * 
   * @param id
   *          唯一标识
   * @param keyword
   *          关键字（标红）
   * @return 配置项故障（资产）履历界面
   */
  @RequestMapping("ciFailureResume")
  public ModelAndView ciResumeIncident(String id) {
    // ModelAndView mv = this.getModelAndView();

    ModelAndView mv = new ModelAndView(this.getModulePath()
        + "/ciFailureResume");

    if (StringUtils.isNotEmpty(id)) {

      List<Map<String, Object>> list = confCiService.findCiIncidentDetail(id);
      mv.addObject("incedentEntities", list);
    }
    return mv;

  }

  /**
   * 配置项数据修改履历
   * 
   * @param id
   *          唯一标识
   * @return 配置项数据修改履历界面
   */
  @RequestMapping("ciDataChangedLog")
  public ModelAndView ciResumeDataLog(String id) {
    // ModelAndView mv = this.getModelAndView();
    ModelAndView mv = new ModelAndView(this.getModulePath()
        + "/ciDataChangedLog");

    if (StringUtils.isNotEmpty(id)) {

      List<Map<String, Object>> dataChangeList = confCiPropertyDatalogService
          .findByBusinessId(id);
      mv.addObject("dataChangeEntities", dataChangeList);

    }
    return mv;

  }

  // ～ ---------------------------end ci 履历--------------------------

  // ～ ---------------------------客户ci -----------------------------

  /**
   * 客户ci的列表
   * 
   * @param customerId
   *          客户id
   * @param request
   *          数据请求
   * @return 结果列表
   */
  @RequestMapping("listCustomerCi")
  @ResponseBody
  public PageResponse<Map<String, Object>> listCustomerCi(String customerId,
      JqGridRequest request) {
    if (StringUtils.isNotEmpty(customerId)) {
      request.addFilterRule("cus_customer_id", JqGridFilterRuleOp.eq,
          customerId);
    }

    return this.getService().findAllDetailByRequest(request).toPage();
  }

  @RequestMapping("listProjectCi")
  @ResponseBody
  public PageResponse<ConfCi> listProjectCi(String projectId,
      JqGridRequest request) {
    if (StringUtils.isNotEmpty(projectId) && !projectId.equals("null")) {
      // 根据项目ID 获取所有客户ID 可能多个
      request
          .setSearchString(" cus_customer_id in(SELECT cus_customer_id FROM proj_project WHERE id='"
              + projectId + "')");
    }
    return this.getService().findAll(request).toPage();
  }

  @RequestMapping("listProjects")
  @ResponseBody
  public List<Map<String, Object>> listProjects(String ciId) {
    // 根据资产扩展信息中的合同编号获取项目
    String sql = "SELECT * FROM proj_project WHERE contract_no=(SELECT VALUE FROM v_conf_property WHERE NAME='合同编号' AND conf_ci_id='"
        + ciId + "')";
    JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
    List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);

    return list;

  }

  /**
   * 客户ci的统计
   * 
   * @param customerId
   *          客户id
   * @return 统计树列表
   */
  @RequestMapping("getCustomerCiCategoryMenu")
  @ResponseBody
  public List<ITreeNode> getCustomerCiCategoryMenu(String customerId) {
    JqGridFilterRule rule = null;

    if (StringUtils.isEmpty(customerId)) {
      rule = new JqGridFilterRule();
    } else {
      rule = new JqGridFilterRule("cus_customer_id", JqGridFilterRuleOp.eq,
          customerId);
    }

    return this.getService().getCiMenu("conf_category_id",
        "conf_category_name", rule);
  }

  // ～ ---------------------------end 客户ci -----------------------------

  public void excelExport(Map<String, Object> model, HSSFWorkbook workbook,
      HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    String excelName = model.get("filePath") == null ? "导出数据.xls" : model.get(
        "filePath").toString();

    // 设置response方式,使执行此controller时候自动出现下载页面,而非直接使用excel打开
    response.setContentType("APPLICATION/OCTET-STREAM");
    response.setHeader("Content-Disposition", "attachment; filename="
        + URLEncoder.encode(excelName, "UTF-8"));

  }

  @RequestMapping("getDyChangeCiProperty")
  @ResponseBody
  public ResultMessage getDyChangeCiProperty(JqGridRequest request,
      HttpServletRequest req) {
    StringBuilder sb = new StringBuilder();
    String ciId = req.getParameter("ciId");
    String tecServiceId = req.getParameter("tecServiceId");
    List<Map<String, Object>> clist = new ArrayList<Map<String, Object>>();
    Map<String, Object> ci = this.getService().findOneToMap(ciId);
    String ciCategoryId = ci.get("conf_category_id").toString();
    // 如果有技术服务目录，根据技术服务目录显示设定的字段

    if (StringUtils.isNotEmpty(tecServiceId)) {
      String[] temArr = tecServiceId.split(",");
      String inStr = "";
      for (String s : temArr) {
        inStr += "'" + s + "',";
      }
      inStr = inStr.substring(0, inStr.length() - 1);
      clist = this.getService().findCiUseChgColumns(inStr, ciCategoryId);

      String sql = "select count(1) count_c from TEC_SERVICE_RELATE_CONF a left join tec_service_relate_ci_category b on a.tec_relate_ci_category_id=b.id where type='扩展' AND ( (SELECT c.treenode_path FROM conf_category c WHERE c.id='"
          + ciCategoryId
          + "') LIKE CONCAT(CONCAT('%',b.ci_category_id),'%')) and a.TEC_SERVICE_ID in ("
          + inStr + ") ";
      JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
      Integer countC = jdbcTemplate.queryForObject(sql, Integer.class);
      if (clist.size() == 0 && countC == 0) {
        clist = this.getService().findCiUseChgColumns();
      }
    } else {
      clist = this.getService().findCiUseChgColumns();
    }

    // 获取需要变更的字段
    // 1.先处理基本属性
    String curFiledCategoryName = "";
    List<String> filedCategoryHeadList = new ArrayList<String>();
    for (Map<String, Object> m : clist) {
      String columnName = m.get("column_name").toString();
      String columnChName = m.get("name").toString();
      String oldValue = "";
      String filedCategoryName = "";
      if (m.get("filed_category_name") != null)
        filedCategoryName = m.get("filed_category_name").toString();//
      curFiledCategoryName = filedCategoryName;

      String columnControlValue = "";

      if (ci.get(columnName) != null) {
        oldValue = ci.get(columnName).toString();
      } else if (ci.get(columnName.toLowerCase()) != null) {
        oldValue = ci.get(columnName.toLowerCase()).toString();
      }
      String columnId = columnName;
      if (m.get("content_value") != null) {
        columnControlValue = m.get("content_value").toString();// 数据字典
      }
      DbEntityFieldToUiControler dfTc = null;
      try {
        dfTc = JsonBuilder.buildNormalBinder().fromJson(columnControlValue,
            DbEntityFieldToUiControler.class);
      } catch (Exception ex) {
        continue;
      }
      String controlType = "";
      String inputType = "input";
      String concrolValueId = "";
      if (dfTc != null) {
        controlType = dfTc.getControlType();
        if (controlType == null)
          controlType = "";
        inputType = dfTc.getInputType();
        if (inputType == null)
          inputType = "input";
        concrolValueId = dfTc.getValueControlId();
        if (concrolValueId == null)
          concrolValueId = "";
      }

      String columnControlValueReal = "";
      switch (inputType) {
      case "select":
        String optionStr = "";
        columnControlValueReal = "<select id='" + columnId + "' name='"
            + columnId + "'>";
        String appDictCode = dfTc.getAppDictCode();
        {
          AppDictService appDictService = ContextHolder
              .getSpringBean("appDictService");
          List<AppDict> types = appDictService.findByType(appDictCode);
          for (AppDict ap : types) {
            if (ap.getName().equals(oldValue)) {
              optionStr += "<option selected=\"selected\">" + ap.getName()
                  + "</option>";
            } else {
              optionStr += "<option>" + ap.getName() + "</option>";
            }

          }
        }
        columnControlValueReal += optionStr + "</select>";
        // 判断需要添加的控件类型
        break;
      case "input":
        switch (controlType) {
        case "date":
          oldValue = oldValue.split(" ")[0];
          // oldValue = DateStringPattern(oldValue,
          // "yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd");
          columnControlValueReal += "<input id='" + columnId + "' name='"
              + columnId + "' value='" + oldValue + "' type='date' />";
          break;
        case "chosePerson":
          String vidValue = "";
          if (ci.get(concrolValueId) != null)
            vidValue = ci.get(concrolValueId).toString();
          columnControlValueReal += "<input id='" + concrolValueId
              + "' type='hidden' name='" + concrolValueId + "' value='"
              + vidValue + "'><input class='selector-input' id='" + columnId
              + "' name='" + columnId + "' value='" + oldValue
              + "' onclick=\"choseControl({controlOldValue:'" + oldValue
              + "',id:'" + columnId + "',valueControlId:'" + concrolValueId
              + "',controlType:'" + controlType + "'})\"/>";
          break;
        default:
          columnControlValueReal += "<input style='width:80%' id='" + columnId
              + "' name='" + columnId + "' value='" + oldValue + "' />";
          break;
        }

        // 判断需要添加的控件类型
        break;
      case "textarea":
        columnControlValueReal += "<textarea id='" + columnId + "' name='"
            + columnId + "'>" + oldValue + "</textarea>";
        break;
      default:
        columnControlValueReal = "<input style='width:80%' id='" + columnId
            + "' name='" + columnId + "'  value='" + oldValue + "'/>";
        break;

      }
      if (!filedCategoryHeadList.contains(curFiledCategoryName)
          && StringUtils.isNotEmpty(filedCategoryName)) {
        sb.append("<tr><td colspan='3' align='left'><div class='gdhead' style='font-weight:bold;'>"
            + filedCategoryName + "</div></td></tr>");
        filedCategoryHeadList.add(curFiledCategoryName);
      }
      sb.append("<tr><td id='td_cname_" + columnId + "'>" + columnChName
          + "</td>");
      sb.append("<td align=center>" + oldValue + "</td>");
      sb.append("<td align=left>" + columnControlValueReal);
      sb.append("</td></tr>");

    }
    // 载入自定义属性
    /*
     * ConfCategoryPropertyService confCategoryPropertyService =
     * ContextHolder.getSpringBean("confCategoryPropertyService");
     * List<Map<String, Object>> list =
     * confCategoryPropertyService.findAllProperty( categoryId);
     */
    return new ResultMessage(true, sb.toString());
  }

  // 根据变更ID，获取某配置项计划变更值（包括基本与扩展属性的值）
  @RequestMapping("getPlanChangeCiValueByChangeId")
  @ResponseBody
  public ResultMessage getPlanChangeCiValueByChangeId(HttpServletRequest req) {
    String changeId = req.getParameter("changeId");
    String ciId = req.getParameter("ciId");
    List<Map<String, Object>> l1 = this.chgChangeConfigurationService
        .getPlanChangeCiValueByChangeId(changeId, ciId);
    return ResultMessage.success(l1);
  }

  @RequestMapping("saveChangePropertyColumn")
  @ResponseBody
  public ResultMessage saveChangePropertyColumn(HttpServletRequest req) {
    String changeId = req.getParameter("changeId");
    // 资产变更流程，在审批后才更新资产属性
    if (changeId != null && !changeId.equals("")) {
      String changeConfigurationList = req
          .getParameter("changeConfigurationList");

      // 如果是在资产变更保存资产配置，则执行资产变更保存策略
      ChgChangeConfiguration[] chgconfArr = JsonBuilder.buildNormalBinder()
          .fromJson(changeConfigurationList, ChgChangeConfiguration[].class);
      if (chgconfArr != null && chgconfArr.length > 0) {
        for (ChgChangeConfiguration item : chgconfArr) {
          String tchangeId = item.getChangeId();
          String ciId = item.getCiId();
          String columnkey = item.getColumnkey();
          chgChangeConfigurationService.deleteChangeConfCi(tchangeId, ciId,
              columnkey);
          chgChangeConfigurationService.saveOrUpdate(item);
        }
        return ResultMessage.success("OK");
      } else {
        return ResultMessage.success("OK");
      }
    }
    return ResultMessage.success("OK");
  }

  public final String DateStringPattern(String date, String oldPattern,
      String newPattern) {
    if (date == null || oldPattern == null || newPattern == null || date == "")
      return "";
    SimpleDateFormat sdf1 = new SimpleDateFormat(oldPattern); // 实例化模板对象
    SimpleDateFormat sdf2 = new SimpleDateFormat(newPattern); // 实例化模板对象
    Date d = null;
    try {
      d = sdf1.parse(date); // 将给定的字符串中的日期提取出来
    } catch (Exception e) { // 如果提供的字符串格式有错误，则进行异常处理
      e.printStackTrace(); // 打印异常信息
    }
    return sdf2.format(d);
  }

  @RequestMapping("getTwoDimension")
  @ResponseBody
  public void getTwoDimension(HttpServletResponse response,
      HttpServletRequest req) {
    MatrixToImageWriters matrixToImageWriters = new MatrixToImageWriters();
    try {
      String code = req.getParameter("code").toString();
      matrixToImageWriters.getTwoDimension(code, response, 170, 170);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @RequestMapping("autocompleteProvlist")
  @ResponseBody
  public List<ConfCi> autocompleteProvlist(JqGridRequest request,
      HttpServletRequest req) {
    String term = req.getParameter("term");
    List<ConfCi> result = null;
    if (StringUtils.isNotEmpty(term)) {
      request.isPageable(false);
      request.setRows(10);
      request.setSelectColumns("provider");
      request.setGroupBy("provider");
      request
          .setSearchString(" (provider is not null) and (upper(provider) LIKE '%"
              + term.toUpperCase() + "%') ");
    }
    result = this.getService().findAll(request);

    return result;

  }

  @RequestMapping("autocompletelist")
  @ResponseBody
  public List<ConfCi> autocompletelist(JqGridRequest request,
      HttpServletRequest req) {
    String term = req.getParameter("term");
    String projectId= req.getParameter("projectId");
    String searchStr="";
    
    if (StringUtils.isNotEmpty(projectId) && !projectId.equals("null")) {
      // 根据项目ID 获取所有客户ID 可能多个
      searchStr+="cus_customer_id in(SELECT cus_customer_id FROM proj_project WHERE id='"
          + projectId + "') and ";
    }
    if (StringUtils.isNotEmpty(term)) {
      request.isPageable(false);
      request.setRows(15);
      request.setSelectColumns("id", "code", "name", "asset_code");
      searchStr+="  (name LIKE '%" + term + "%' OR   code LIKE '%"
          + term + "%' OR  asset_code LIKE '%" + term + "%')";
      request.setSearchString(searchStr);
      return this.getService().findAll(request);
    } else {
      return this.getService().findAll(request);
    }
  }

  @RequestMapping("getSeqByTableName")
  @ResponseBody
  public String getSeqByTableName(String tableName, HttpServletRequest req) {
    SequenceGenerator sg = ContextHolder.getSpringBean("sequenceGenerator");
    String seq = sg.next(tableName);
    return seq;

  }

  @Override
  @RequestMapping("listDetail")
  @ResponseBody
  public PageResponse<Map<String, Object>> listDetail(JqGridRequest request,
      HttpServletRequest req) {
    String areCompany = req.getParameter("areCompany");
    String dtshowdiscard = req.getParameter("dtshowdiscard");
    if (StringUtils.isNotEmpty(areCompany) && areCompany.equals("1")) {
      request.addFilterRule("are_company", JqGridFilterRuleOp.eq, "1");
    }
    if (StringUtils.isNotEmpty(dtshowdiscard) && dtshowdiscard.equals("t")) {
      request.setSearchString(" status not in('在库坏件','报废','已报废') ");
    }

    return this.getService().findAllDetailByRequest(request).toPage();

  }

  @RequestMapping("getSimilarCategoryByName")
  @ResponseBody
  public Map<String, Object> getSimilarCategoryByName(JqGridRequest request,
      String name, HttpServletRequest req) {
    return this.getService().getSimilarCategoryByName(name);

  }

}
